package com.wing.order.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.enterprise.feign.EnterpriseClient;
import com.wing.enterprise.product.model.response.ProductDetailVO;
import com.wing.order.model.entity.Purchase;
import com.wing.order.model.request.PurchaseForm;
import com.wing.order.model.response.PurchaseVO;
import com.wing.order.service.PurchaseService;
import com.wing.platform.cabinet.Supplier;
import com.wing.platform.feign.PlatformClient;
import com.wing.user.feign.UserClient;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-采购管理", tags = "#/order/purchase")
@RestController("purchaseController")
@RequestMapping("order/admin/purchase")
@Slf4j
@RequiredArgsConstructor
public class PurchaseController {

    private final PurchaseService purchaseService;

    private final PlatformClient platformClient;

    private final UserClient userClient;

    private final EnterpriseClient enterpriseClient;


    @ApiOperation(value = "查询所有采购", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<Purchase> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,@RequestParam(value = "status",required = false)String status
            ,@RequestParam(value = "code",required = false)String code
    ){

        Page<Purchase> pg = new Page<>(page, limit);
        QueryWrapper<Purchase> queryWrapper = new QueryWrapper<>();
        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            if (StringUtils.equals("asc", order)) {
                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(sort));
            } else {
                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(sort));
            }
            if (StringUtils.isNotBlank(status)){
                queryWrapper.eq("status",Purchase.Status.valueOf(status));
            }
            if (StringUtils.isNotBlank(code)){
                queryWrapper.eq("code",code);
            }
        }

        //搜索

        IPage<Purchase> list = purchaseService.getBaseMapper().selectPage(pg, queryWrapper);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加采购", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(PurchaseForm.Add.class) PurchaseForm purchaseForm) {
        if (purchaseService.add(purchaseForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }




    @ApiOperation(value = "修改采购", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(PurchaseForm.Update.class) PurchaseForm purchaseForm) {
        Purchase purchase = purchaseService.getById(purchaseForm.getId());
        if(purchase == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(Purchase.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(purchaseForm, purchase, copyOptions);
        if (purchaseService.updateById(purchase)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



@ApiOperation(value = "删除采购", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "purchaseId", value = "采购id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long purchaseId) {
        if (purchaseService.removeById(purchaseId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    /**
     * 选择供应商接口
     */
    @GetMapping("/getSupplier")
    public PageResult<Supplier> getSupplier(){
        return platformClient.getSupplier("",1,999,"create_time","asc");
    }

    /**
     * 查询当前登录用户
     */
    @GetMapping("/getLoginUser")
    public JsonResult getLoginUser(){
        return JsonResult.success("",JwtUtils.getLoginUsername());
    }
    /**
     * 查询订单审核人
     */
    @GetMapping("/getOrderAuditor")
    public JsonResult getOrderAuditor(){
        return userClient.getAll();
    }

    /**
     * 查询在库产品信息
     */
    @GetMapping("/getInventoryProduct")
    public PageResult<ProductDetailVO> getInventoryProduct(
            @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit
            , @RequestParam(defaultValue = "create_time") String sort
            , @RequestParam(defaultValue = "asc") String order
            ,@RequestParam(value = "skuName",required = false) String skuName
            ,@RequestParam(value = "skuCode",required = false) String skuCode
            ,@RequestParam(value = "productCategoryId",required = false) Long productCategoryId
            ,@RequestParam(value = "id",required = false) Long id
    ){
        PageResult<ProductDetailVO> list = enterpriseClient.getInventoryProductDetailPageList(page,limit,skuName,skuCode,productCategoryId,id,null);

/*        for (int i = 0; i <list.getData().size() ; i++) {
            list.getData().get(i).setMarketPrice(list.getData().get(i).getSupplyPrice());
            if (list.getData().get(i).getInventory()<=0){
              list.getData().remove(i);
            }
        }*/
        return new PageResult<>(list.getData(), list.getCount());
    }

    /**
     * 提交采购订单
     */
    @PostMapping("/addPurchase")
    public JsonResult addPurchase(@RequestBody PurchaseForm purchaseForm){

        try {
            if (purchaseService.addPurchase(purchaseForm)>0){
                return JsonResult.success("添加成功");
            }
            log.error("addPurchase fail");
            return JsonResult.fail("添加失败,缺少产品信息");
        }catch (Exception e){
            log.error("addPurchase fail"+e);
            return JsonResult.fail("添加失败,缺少产品信息");
        }
    }

    /**
     * 采购入库计划列表
     */
    @GetMapping("/getPurchaseList")
    public PageResult<PurchaseVO> getPurchaseList(
            @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit
            , @RequestParam(defaultValue = "create_time") String sort
            , @RequestParam(defaultValue = "desc") String order
    ){
        Page<PurchaseVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        IPage<PurchaseVO> list = purchaseService.pageList4app(pg,params);

        return new PageResult<>(list.getRecords(), list.getTotal());
    }


}
